package com.gorkr;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author gorkr
 * @date 2022/07/25 12:58
 **/
public class E415AddStrings {

    public String addStrings(String num1, String num2) {
        StringBuilder res = new StringBuilder();

        num1 = new StringBuilder(num1).reverse().toString();
        num2 = new StringBuilder(num2).reverse().toString();

        char[] chars1 = num1.toCharArray();
        char[] chars2 = num2.toCharArray();

        int end1 = chars1.length - 1;
        int end2 = chars2.length - 1;

        int i = 0;
        // 进位
        int flg = 0;
        while (i <= end1 && i <= end2) {

            int sum = chars1[i] + chars2[i] + flg;
            // 位之和
            sum = sum - '0' - '0';
            if (sum > 9) {
                sum -= 10;
                flg = 1;
            } else {
                flg = 0;
            }
            res.append(sum);
            i++;
        }
        if (end1 > end2) {
            for (int j = i ; j <= end1; j++) {
                int sum = chars1[j] + flg;
                sum = sum - '0';
                if (sum > 9) {
                    sum -= 10;
                    flg = 1;
                } else {
                    flg = 0;
                }
                res.append(sum);

            }
        } else if (end1 < end2) {
            for (int j = i ; j <= end2; j++) {
                int sum = chars2[j] + flg;
                sum = sum - '0';
                if (sum > 9) {
                    sum -= 10;
                    flg = 1;
                } else {
                    flg = 0;
                }
                res.append(sum);

            }
        }
        if(flg!=0){
            res.append(flg);
        }



        return res.reverse().toString();
    }

    public String addStrings2(String num1, String num2){
        StringBuilder res = new StringBuilder();
        int len1 = num1.length()-1;
        int len2 = num2.length()-1;

        int flg = 0;

        while (len1>=0||len2>=0){
            int a = len1>=0?num1.charAt(len1)-'0':0;
            int b = len2>=0?num2.charAt(len2)-'0':0;
            int sum = a + b + flg;
            res.append(sum%10);
            flg = sum / 10;
            len1--;
            len2--;
        }
        if(flg!=0){
            res.append(flg);
        }
        return res.reverse().toString();

    }

    @Test
    public void test() {

        // 11
        // 321
        System.out.println(addStrings2("9", "99"));
    }

}
    